package com.ubivelox.uienginesample;


import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

public class Buffers {
	// vertex buffer.
	private FloatBuffer mVerticesBuffer = null;

	// index buffer.
	private ShortBuffer mIndicesBuffer = null;

	// color buffer.
	private FloatBuffer mColorBuffer = null;
	
	// Texture Buffer.
	private FloatBuffer mTexturesBuffer = null;

	// number of indices.
	private int mNumOfIndices = -1;

	public void draw(GL10 gl) {
		
		gl.glFrontFace(GL10.GL_CCW);
		
		gl.glEnable(GL10.GL_CULL_FACE);
		gl.glCullFace(GL10.GL_BACK);
		
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVerticesBuffer);
		gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexturesBuffer);

		gl.glDrawElements(GL10.GL_TRIANGLES, mNumOfIndices,
				GL10.GL_UNSIGNED_SHORT, mIndicesBuffer);

		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		
		gl.glDisable(GL10.GL_CULL_FACE);
	}

	protected void setVertices(float[] vertices) {
		// a float is 4 bytes, therefore we multiply the number if
		// vertices with 4.
		ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
		vbb.order(ByteOrder.nativeOrder());
		mVerticesBuffer = vbb.asFloatBuffer();
		mVerticesBuffer.put(vertices);
		mVerticesBuffer.position(0);
	}

	protected void setIndices(short[] indices) {
		// short is 2 bytes, therefore we multiply the number if
		// vertices with 2.
		ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2);
		ibb.order(ByteOrder.nativeOrder());
		mIndicesBuffer = ibb.asShortBuffer();
		mIndicesBuffer.put(indices);
		mIndicesBuffer.position(0);
		mNumOfIndices = indices.length;
	}

	protected void setColors(float[] colors) {
		// float has 4 bytes.
		ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * 4);
		cbb.order(ByteOrder.nativeOrder());
		mColorBuffer = cbb.asFloatBuffer();
		mColorBuffer.put(colors);
		mColorBuffer.position(0);
	}
	
	
	protected void setTextures(float[] textures) {
		// float has 4 bytes.
		ByteBuffer cbb = ByteBuffer.allocateDirect(textures.length * 4);
		cbb.order(ByteOrder.nativeOrder());
		mTexturesBuffer = cbb.asFloatBuffer();
		mTexturesBuffer.put(textures);
		mTexturesBuffer.position(0);
	}

}
